package com.example.administrator.hello108zct;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private EditText et;
    private Button btn;
    private TextView tv;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch(msg.what)
            {
                case 1:
                    ByteArrayOutputStream baos = (ByteArrayOutputStream)msg.obj;
                    tv.setText(baos.toString());
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et = (EditText)this.findViewById(R.id.editText);
        btn = (Button)this.findViewById(R.id.button);
        tv = (TextView)this.findViewById(R.id.textView);
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
               final String urlStr= et.getText().toString();
                new Thread(){
                    @Override
                    public void run(){
                        super.run();
                        try{
                            URL url=new URL(urlStr);
                            HttpURLConnection conn=(HttpURLConnection)url.openConnection();
                            InputStream is=conn.getInputStream();
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            byte [] data = new byte[1024];
                            while(is.read(data)!=-1)
                            {
                                baos.write(data);
                            }
                           // tv.setText(baos.toString());
                            Message msg = new Message();
                            msg.what = 1;
                            msg.obj = baos;
                            handler.sendMessage(msg);

                        }catch(Exception e)
                        {
                            System.out.println(e.getMessage().toString());
                        }
                    }
                };
        //tv.setText(et.getText().toString());
            }
        });
    }
}


